package com.example.oauthserver.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.example.oauthserver.model.UserDO;
import com.example.oauthserver.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

import java.util.Map;

public class MyTokenStoreService extends JwtTokenStore {
    @Autowired
    private UserRepository userRepository;
    /**
     * Create a JwtTokenStore with this token enhancer (should be shared with the DefaultTokenServices if used).
     *
     * @param jwtTokenEnhancer
     */
    public MyTokenStoreService(JwtAccessTokenConverter jwtTokenEnhancer) {
        super(jwtTokenEnhancer);
    }

    @Override
    public void storeAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) {
        String accessToken = token.getValue();
        Map<String,String> map = authentication.getOAuth2Request().getRequestParameters();
        String clientType = map.getOrDefault("client_type","PC");
        String username = authentication.getName();
        String usernameAndClientType = username.concat("-").concat(clientType);
        Integer tokenValiditySeconds = Integer.valueOf(map.get("token_validity_seconds"));
        UserDO userDO = userRepository.findByUsername(username);
        System.err.println("userDO=" + JSONObject.toJSONString(map,true));
        // TODO: 2021/10/9 保存数据到redis中
        super.storeAccessToken(token, authentication);
    }
}
